<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row>
        <!-- 添加角色按钮区域 -->
        <el-button type="primary" @click="addRoleDialogVisible = true"
          >添加角色</el-button
        >
        <el-table :data="RolesList" stripe border>
          <!-- 展开列 -->
          <el-table-column type="expand">
            <!-- eslint-disable-next-line -->
            <template slot-scope="scope">
              <el-row
                v-for="(item1, i1) in scope.row.children"
                :key="item1.id"
                :class="['bdBottom', i1 === 0 ? 'bdTop' : '', 'vcenter']"
              >
                <!-- 渲染一级权限 -->
                <el-col :span="5">
                  <el-tag
                    closable
                    @close="removeRightById(scope.row, item1.id)"
                    >{{ item1.authName }}</el-tag
                  >
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 渲染二级和三级权限 -->
                <el-col :span="19">
                  <!-- 通过 for 循环 嵌套渲染二级权限 -->
                  <el-row
                    :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']"
                    v-for="(item2, i2) in item1.children"
                    :key="item2.id"
                  >
                    <el-col :span="6">
                      <el-tag
                        type="success"
                        closable
                        @close="removeRightById(scope.row, item2.id)"
                        >{{ item2.authName }}</el-tag
                      >
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <el-col :span="18">
                      <el-tag
                        type="warning"
                        v-for="item3 in item2.children"
                        :key="item3.id"
                        closable
                        @close="removeRightById(scope.row, item3.id)"
                        >{{ item3.authName }}</el-tag
                      >
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
              <!-- <pre>
                {{ scope.row }}
              </pre> -->
            </template>
          </el-table-column>
          <!-- 索引列 -->
          <el-table-column type="index" label="#"> </el-table-column>
          <el-table-column prop="roleName" label="角色名称"> </el-table-column>
          <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
          <el-table-column label="操作">
            <!-- eslint-disable-next-line -->
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit">编辑</el-button>
              <el-button type="danger" icon="el-icon-delete">删除</el-button>
              <el-button
                type="warning"
                icon="el-icon-setting"
                @click="showSetRightDialog(scope.row)"
                >分配权限</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-row>
    </el-card>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="setdialogVisible"
      width="50%"
      @close="RightDialogClose"
    >
      <!-- 树形组件 -->
      <el-tree
        :data="RightDialogList"
        :props="treeProps"
        node-key="id"
        default-expand-all
        show-checkbox
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色对话框 -->

    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      width="50%"
    >
      <el-form
        :model="roleForm"
        :rules="roleRules"
        ref="roleRuleFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="roleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 添加角色底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 所有角色列表数据
      RolesList: [],
      // 控制分配权限对话框的显示与隐藏
      setdialogVisible: false,
      // 分配权限的数据
      RightDialogList: [],
      // 树形控件的属性绑定
      treeProps: {
        children: "children",
        label: "authName",
      },
      // 默认选中的节点id值数组
      defKeys: [],
      roleId: "",
      // 控制添加角色对话框的显示与隐藏
      addRoleDialogVisible: false,
      // 获取角色列表的数据
      roleForm: { roleName: "", roleDesc: "" },
      // 添加角色列表的校验规则
      roleRules: {
        roleName: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        roleDesc: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    //   获取所有角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      //   console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败");
      }
      this.RolesList = res.data;
      // console.log(this.RolesList);
    },
    // 删除标签
    async removeRightById(role, rightId) {
      const restuleConfirm = await this.$confirm(
        "此操作将永久删除该标签, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (restuleConfirm !== "confirm") {
        return this.$message.info("取消了删除!");
      }
      console.log("确认了删除!");
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      );
      if (res.meta.status !== 200) {
        return this.$message.error("删除信息失败");
      }
      role.children = res.data;
    },
    // 获取分配权限数据
    async showSetRightDialog(role) {
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        return this.$message.error("获取分配权限失败");
      }
      // 把获取到的数据保存在data中
      this.RightDialogList = res.data;
      console.log(this.RightDialogList);
      // 获取3级节点的id
      this.getleafKeys(role, this.defKeys);
      this.setdialogVisible = true;
      this.roleId = role.id;
    },
    // 通过递归的形式，获取角色下所有三级权限的id，并保存到 defKeys 数组中
    getleafKeys(node, arr) {
      // 如果当前 node 节点不包含 children 属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getleafKeys(item, arr);
      });
    },
    // 监听分配权限关闭事件
    RightDialogClose() {
      this.defKeys = [];
    },
    // 点击为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];

      const keysStr = keys.join(",");
      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: keysStr }
      );

      if (res.meta.status !== 200) {
        return this.$message.error("获取角色权限失败！");
      }
      this.$message.success("获取角色权限成功！");
      this.getRolesList();
      this.setdialogVisible = false;
    },
    // 添加角色列表
    addRoles() {
      this.$refs.roleRuleFormRef.validate(async (valid) => {
        console.log(valid);
        const { date: res } = await this.$http.post("roles", this.roleForm);
        console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.error("发送角色信息失败！");
        }
        this.$message.success("发送角色信息成功！");

        this.getRolesList();
      });
      this.addRoleDialogVisible = false;
    },
  },
};
</script>

<style lang="less" scoped>
.el-row {
  margin: 10px;
}
.bdTop {
  border-top: 1px solid #eee;
}
.bdBottom {
  border-bottom: 1px solid #eee;
}
i {
  margin-left: 10px;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>